#include "fromkcode.h"


int main(int argc, char **argv)
{
  if(argc != 2)
  {
    printf("Usage: %s <KCode>\n", argv[0]);
    return 0;
  }
  init_r_maps();

  float lu,la;
  convert((char*)argv[1],9,lu,la);
  printf("%f,%f\n",lu,la);

  return 0;
}

int convert34to10(const char* num34, int len) {
  int num10 = 0;
  for(int i = 0; i < len; ++i) {
    assert(IS_NUM(num34[i]));
    num10 += r_maps[ num34[i] ] * pow34(i);
  }

  return num10;
}

int pow34(int i) {
  int sum = 1;
  while(i > 0) {
    sum *= 34;
    --i;
  }
  return sum;
}

int convert(char* num34, int len, float& ltu, float& lat) {
  printf("%s\n", num34);
  assert(len == 9);
  int quad = *num34;// k码的第一位，5678的一个，标识哪个象限。
  printf("-----quad = %c\n", *num34);
  char *pltu = num34 + 1;
  char *plat = num34 + 5;
  switch(quad) {
    case '5': 
      ltu = convert34to10(pltu, 4);
      lat = convert34to10(plat, 4);
      ltu = (float)ltu / (3600 * 10) + 105;
      lat = (float)lat / (3600 * 10) + 40;
      break;
    case '6':
      ltu = convert34to10(pltu, 4);
      lat = convert34to10(plat, 4);
      ltu = (float)ltu / (3600 * 10) + 70;
      lat = (float)lat / (3600 * 10) + 40;
      break;
    case '7':
      ltu = convert34to10(pltu, 4);
      lat = convert34to10(plat, 4);
      ltu = (float)ltu / (3600 * 10) + 70;
      lat = (float)lat / (3600 * 10) + 5;
      break;
    case '8':
      ltu = convert34to10(pltu, 4);
      lat = convert34to10(plat, 4);
      ltu = (float)ltu / (3600 * 10) + 105;
      lat = (float)lat / (3600 * 10) + 5;
      break;
  }
  return 0;
}

void init_r_maps() {
  memset(r_maps, 0, 255);
  r_maps['0'] = 0;
  r_maps['1'] = 1;
  r_maps['2'] = 2;
  r_maps['3'] = 3;
  r_maps['4'] = 4;
  r_maps['5'] = 5;
  r_maps['6'] = 6;
  r_maps['7'] = 7;
  r_maps['8'] = 8;
  r_maps['9'] = 9;
  r_maps['a'] = 10;
  r_maps['b'] = 11;
  r_maps['c'] = 12;
  r_maps['d'] = 13;
  r_maps['e'] = 14;
  r_maps['f'] = 15;
  r_maps['g'] = 16;
  r_maps['h'] = 17;
  r_maps['i'] = 18;
  r_maps['j'] = 19;// 没有l；
  r_maps['k'] = 20;
  r_maps['m'] = 21;
  r_maps['n'] = 22;// 没有o；
  r_maps['p'] = 23;
  r_maps['q'] = 24;
  r_maps['r'] = 25;
  r_maps['s'] = 26;
  r_maps['t'] = 27;
  r_maps['u'] = 28;
  r_maps['v'] = 29;
  r_maps['w'] = 30;
  r_maps['x'] = 31;
  r_maps['y'] = 32;
  r_maps['z'] = 33;
}